package com.iraeta.api;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.iraeta.HikConfig;
import com.iraeta.entity.Fangkerecord;
import com.iraeta.entity.ProcessStatus;
import com.iraeta.entity.RecordsRequest;
import com.iraeta.entity.ShenHeStatus;
import com.iraeta.uitl.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(value = "hikApi")
public class HikApi {
    private static final Logger logger = LoggerFactory.getLogger(HikApi.class);

    @Autowired
    private HikConfig hikConfig;

    public final String  ARTEMIS_PATH = "/artemis";

    public List<Fangkerecord> fangKeList() throws Exception{
        String url = ARTEMIS_PATH + "/api/iccm/v2/visiting/records";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", url); //Key 为协议，Value 为接口路径
            }
        };
        RecordsRequest recordsRequest = new RecordsRequest();
        recordsRequest.setPageNo(1);
        recordsRequest.setPageSize(1000);
        recordsRequest.setInvoicesStatus(0);        //状态0 是查询未审批的数据
        String body = JSON.toJSONString(recordsRequest);
        String result = ArtemisHttpUtil.doPostStringArtemis(new ArtemisConfig(hikConfig.getHost(), hikConfig.getAppkey(), hikConfig.getAppsecret()),
                path, body, null, null,"application/json;charset=UTF-8");
        JSONObject jsonResult = JSONObject.parseObject(result);
        String code = jsonResult.getString("code");
        if(!code.equals("0")){
            throw new RuntimeException("调用HIK接口[visiting/records]错误:" + jsonResult.getString("msg"));
        }
        List<Fangkerecord> fangkerecordList = new ArrayList<>();
        JSONObject jsonResultData = jsonResult.getJSONObject("data");
        JSONArray recordList = jsonResultData.getJSONArray("list");
        for(int i=0; i<recordList.size();i++){
            Fangkerecord fangkerecord = new Fangkerecord();
            JSONObject recordJo = recordList.getJSONObject(i);
            if(recordJo.getString("orderId") == null || recordJo.getString("receptionistId") == null || recordJo.getString("invoiceNo") == null){
                continue;
            }
            fangkerecord.setOrderid(recordJo.getString("orderId"));
            fangkerecord.setInvoiceno(recordJo.getString("invoiceNo"));
            fangkerecord.setReceptionistid(recordJo.getString("receptionistId"));
            fangkerecord.setReceptionistname(recordJo.getString("receptionistName"));
            fangkerecord.setVisitpurpose(recordJo.getString("visitPurpose"));
            String visitStartTime = recordJo.getString("visitStartTime");
            if(visitStartTime == null){
                fangkerecord.setVisitstarttime(DateUtil.parseDate( DateUtil.today()));
            }else{
                String visitStartTimeSplit = visitStartTime.substring(0, 10);
                fangkerecord.setVisitstarttime(DateUtil.parseTime(visitStartTimeSplit));
            }
            JSONObject visitorJo = recordJo.getJSONArray("visitorInfoResDtoList").getJSONObject(0);
            fangkerecord.setVisitorname(visitorJo.getString("visitorName"));
            fangkerecord.setPhoneno(visitorJo.getString("phoneNo"));
            fangkerecord.setProcesserror("");
            fangkerecord.setProcessstatus(ProcessStatus.unProcess);
            fangkerecord.setShenhestatus(ShenHeStatus.unShenHe);
            fangkerecordList.add(fangkerecord);
        }
        return fangkerecordList;
    }

    public String getRenYuanOrgIndexCode(String personIds) throws Exception{
        String url = ARTEMIS_PATH + "/api/resource/v2/person/advance/personList";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", url); //Key 为协议，Value 为接口路径
            }
        };
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("pageNo", 1);
        jsonBody.put("pageSize", 1000);
        jsonBody.put("personIds", personIds);
        String body = jsonBody.toJSONString();

        String result = ArtemisHttpUtil.doPostStringArtemis(new ArtemisConfig(hikConfig.getHost(), hikConfig.getAppkey(), hikConfig.getAppsecret()),
                path, body, null, null,"application/json;charset=UTF-8");
        JSONObject jsonResult = JSONObject.parseObject(result);
        String code = jsonResult.getString("code");
        if(!code.equals("0")){
            throw new RuntimeException("调用HIK接口[person/advance/personList]错误:" + jsonResult.getString("msg"));
        }
        JSONObject jsonResultData = jsonResult.getJSONObject("data");
        JSONObject renYuanJo = jsonResultData.getJSONArray("list").getJSONObject(0);
        if(StrUtil.isEmpty(renYuanJo.getString("orgIndexCode"))){
            throw new RuntimeException("人员获取组织OrgIndexCode失败");
        }
        return renYuanJo.getString("orgIndexCode");
    }

    public List<String> getOrgShenHeWx(String orgIndexCode) throws Exception{
        String url = ARTEMIS_PATH + "/api/resource/v2/person/orgIndexCode/personList";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", url); //Key 为协议，Value 为接口路径
            }
        };
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("pageNo", 1);
        jsonBody.put("pageSize", 1000);
        jsonBody.put("orgIndexCode", orgIndexCode);
        String body = jsonBody.toJSONString();

        String result = ArtemisHttpUtil.doPostStringArtemis(new ArtemisConfig(hikConfig.getHost(), hikConfig.getAppkey(), hikConfig.getAppsecret()),
                path, body, null, null,"application/json;charset=UTF-8");
        JSONObject jsonResult = JSONObject.parseObject(result);
        String code = jsonResult.getString("code");
        if(!code.equals("0")){
            throw new RuntimeException("调用HIK接口[person/advance/personList]错误:" + jsonResult.getString("msg"));
        }
        JSONObject jsonResultData = jsonResult.getJSONObject("data");
        JSONArray renYuanList = jsonResultData.getJSONArray("list");
        List<String> orgShenHeWxList = new ArrayList<>();
        for(int i=0; i<renYuanList.size();i++){
            JSONObject renYuanJo = renYuanList.getJSONObject(i);
            String jonNo = renYuanJo.getString("jobNo");
            if(!StrUtil.isEmpty(jonNo)){
                if(jonNo.startsWith("wx")){
                    orgShenHeWxList.add(jonNo);
                }
            }
        }
        return orgShenHeWxList;
    }

    public void shenHeRecord(String invoiceno, int status) throws Exception{
        String url = ARTEMIS_PATH + "/api/iccm/v1/aprovalRecord/approval";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", url); //Key 为协议，Value 为接口路径
            }
        };
        List<String> orderList = new ArrayList<>();
        orderList.add(invoiceno);
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("approvalResult", status);
        //jsonBody.put("processorId", "de25c2bf328c4def8b3fa4a27321d58f");
        //jsonBody.put("processorId", "7b0bf58b03354702b0a2284b147c4fb9");
        jsonBody.put("processorId", hikConfig.getProcessorid());
        jsonBody.put("orderIdList", orderList);
        String body = jsonBody.toJSONString();
        String result = ArtemisHttpUtil.doPostStringArtemis(new ArtemisConfig(hikConfig.getHost(), hikConfig.getAppkey(), hikConfig.getAppsecret()),
                path, body, null, null,"application/json;charset=UTF-8");
        JSONObject jsonResult = JSONObject.parseObject(result);
        String code = jsonResult.getString("code");
        if(!code.equals("0")){
            throw new RuntimeException(jsonResult.getString("msg"));
        }
    }
}
